package com.icss.ah.email.service;

import java.util.HashMap;
import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.icss.ah.base.util.ResourceLoader;
import com.icss.ah.login.bean.UserInfoBean;
import com.icss.j2ee.util.UUID;

@Service
@Transactional
public class EmailAuthenticateService {

	@Autowired
	private SqlSessionTemplate sqlSessionTemplate;
	private final Logger errlog = Logger.getLogger("E");
	private final Logger infolog = Logger.getLogger("I");
	
	private static final String sendUserName = ResourceLoader.getInstance("icss").getString("sendUserName");// 发送邮件需要连接的服务器的用户名 
	  
	private static final String sendPassword = ResourceLoader.getInstance("icss").getString("sendPassword");// 发送邮件需要连接的服务器的密码 
  
	private static final String sendProtocol = ResourceLoader.getInstance("icss").getString("sendProtocol");// 发送邮件使用的端口 
	
	private static final String sendHostAddress = ResourceLoader.getInstance("icss").getString("sendHostAddress");// 发送邮件使用的服务器的地址 
  
	private static final String logoImg = ResourceLoader.getInstance("icss").getString("logoImg");// 发送邮件平台logo地址
	private static final String logoImgWidth = ResourceLoader.getInstance("icss").getString("logoImgWidth");// 发送邮件平台logo地址
	private static final String logoImgHeight = ResourceLoader.getInstance("icss").getString("logoImgHeight");// 发送邮件平台logo地址
	
	private static final String hostUrl = ResourceLoader.getInstance("icss").getString("hostUrl");// 邮件认证服务域名
	
	/**
	 * 获取用户认证邮箱
	 * @param userCode
	 * @return
	 */
	public String queryUserEmail(String userCode){
		String email = "";
		try{
			email = sqlSessionTemplate.selectOne("EmailAuthenticateBean.queryUserEmail", userCode);
			email = email == null ? "" : email;
		} catch (Exception e) {
			e.printStackTrace();
			errlog.error("EmailAuthenticateService|queryUserEmail|异常：",e);
		}
		return email;
	}
	/**
	 * 获取用户认证邮箱状态
	 * @param userCode
	 * @return
	 */
	public String queryUserEmailAuthenticateStatus(String userCode){
		String status = "";
		try{
			status = sqlSessionTemplate.selectOne("EmailAuthenticateBean.queryUserEmailAuthenticateStatus", userCode);
			status = status == null ? "" : status;
		} catch (Exception e) {
			e.printStackTrace();
			errlog.error("EmailAuthenticateService|queryUserEmailAuthenticateStatus|异常：",e);
		}
		return status;
	}
	
	/**
	 * 邮箱认证
	 * @param userCode
	 * @param emailAddress
	 * @return
	 */
	public String sendEmailAuthenticate(String userCode,String emailAddress,String opeFlag,UserInfoBean userInfo,String functionFlag){
		String result = "0,认证邮件发送异常，请联系管理员！";
		try{
			String uuid = new UUID().toString();
			HashMap hm = new HashMap();
			hm.put("uuid", uuid);
			hm.put("userCode", userCode);
			hm.put("emailAddress", emailAddress);
			hm.put("shopId", userInfo.getShopId());
			hm.put("status", 0);
			//判断用户是否已存在验证邮件记录
			String status = sqlSessionTemplate.selectOne("EmailAuthenticateBean.queryUserEmailAuthenticateStatus", hm);
			infolog.info("EmailAuthenticateService|sendEmailAuthenticate|status:"+status);
			status = status == null ? "" : status;
			if(status.equals("1")&&functionFlag.equals("sendEmailAuthenticate")&&"".equals(opeFlag)){
				result = "1,您已认证邮箱";
			} else {
				if(status.equals("0")){
					//存在则作废已有验证邮件记录
					sqlSessionTemplate.update("EmailAuthenticateBean.updateUserEmailAuthenticateStatus", hm);
					infolog.info("EmailAuthenticateService|sendEmailAuthenticate|update:作废已有验证邮件记录");
				} 
				//新增验证邮件记录
				sqlSessionTemplate.insert("EmailAuthenticateBean.insertUserEmailAuthenticate", hm);
				infolog.info("EmailAuthenticateService|sendEmailAuthenticate|insert:新增验证邮件记录");
				//生成邮件内容
				String hrefUrl = "";
				String content = "";
				boolean sendResult = false;
				if(functionFlag.equals("sendEmailAuthenticate")){
					hrefUrl = hostUrl+"/emailAuthenticate/userAuthenticate?t="+uuid;
					content = formatEmailContent(logoImg, logoImgWidth, logoImgHeight, "完成认证", hrefUrl,functionFlag);
					//发送邮件
					sendResult = sendEmail("邮箱认证", content, emailAddress);
				}else if(functionFlag.equals("sendEmailForResetPwd")){
					hrefUrl = hostUrl+"/emailAuthenticate/doResetPwd?t="+uuid;
					content = formatEmailContent(logoImg, logoImgWidth, logoImgHeight, "重置密码", hrefUrl,functionFlag);
					//发送邮件
					sendResult = sendEmail("重置密码", content, emailAddress);
				}
				if(sendResult){
					if(functionFlag.equals("sendEmailAuthenticate")){
						result = "1,认证邮件发送成功！";
					}else if(functionFlag.equals("sendEmailForResetPwd")){
						result = "1,重置密码邮件发送成功！请去邮箱收取邮件完成重置密码";
					}
				} else {
					if(functionFlag.equals("sendEmailAuthenticate")){
						result = "0,认证邮件发送失败，请确认输入邮箱是否正确！";
					}else if(functionFlag.equals("sendEmailForResetPwd")){
						result = "0,重置密码邮件发送失败，请确认输入邮箱是否正确！";
					}
				}
			}
			
		} catch (Exception e) {
			e.printStackTrace();
			errlog.error("EmailAuthenticateService|sendEmailAuthenticate|异常：",e);
		}
		return result;
	}
	/**
	 * 用户邮箱认证
	 * @param uuid
	 * @return
	 */
	@Transactional
	public String userAuthenticate(HttpServletRequest request,String uuid){
		String result = "ERROR";
		try{
			HashMap infoMap = sqlSessionTemplate.selectOne("EmailAuthenticateBean.queryUserEmailAuthenticate", uuid);
			if(infoMap==null){
				result = "UN_FIND";
			} else {
				String userCode = infoMap.get("PERSON_ACCOUNT") == null ? "" : infoMap.get("PERSON_ACCOUNT").toString();
				request.getSession().setAttribute("userCode", userCode);
				String status = infoMap.get("STATUS") == null ? "" : infoMap.get("STATUS").toString();
				if(status.equals("0")){
					String TIME_CHECK = infoMap.get("TIME_CHECK") == null ? "0" : infoMap.get("TIME_CHECK").toString();
					if(Integer.parseInt(TIME_CHECK)<=0){
						result = "EXPIRED";
					} else {
						infoMap.put("uuid", uuid);
						infoMap.put("status", 1);
						sqlSessionTemplate.update("EmailAuthenticateBean.saveUserEmail",infoMap);
						sqlSessionTemplate.update("EmailAuthenticateBean.saveUserEmailAuthenticate",infoMap);
						result = "SUCCESS";
					}
				} else if(status.equals("1")){
					result = "COMPLETED";
				} else if(status.equals("2")){
					result = "CANCELED";
				} else {
					result = "UN_FIND";
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			errlog.error("EmailAuthenticateService|userAuthenticate|异常：",e);
		}
		return result;
	}
	/**
	 * 重置密码，进入修改密码
	 * @param request
	 * @param uuid
	 * @return
	 */
	@Transactional
	public String doResetPwd(HttpServletRequest request,String uuid){
		String result = "ERROR";
		try{
			HashMap infoMap = sqlSessionTemplate.selectOne("EmailAuthenticateBean.queryLinkIfOverdue", uuid);
			if(infoMap==null){
				result = "UN_FIND";
			} else {
				String userCode = infoMap.get("PERSON_ACCOUNT") == null ? "" : infoMap.get("PERSON_ACCOUNT").toString();
				request.getSession().setAttribute("userCode", userCode);
				String status = infoMap.get("STATUS") == null ? "" : infoMap.get("STATUS").toString();
				if(status.equals("0")){
					String TIME_CHECK = infoMap.get("TIME_CHECK") == null ? "0" : infoMap.get("TIME_CHECK").toString();
					if(Integer.parseInt(TIME_CHECK)<=0){
						result = "EXPIRED";
					} else {
						infoMap.put("uuid", uuid);
						infoMap.put("status", 2);
						sqlSessionTemplate.update("EmailAuthenticateBean.saveUserEmailAuthenticate",infoMap);
						result = "SUCCESS";
					}
				} else if(status.equals("1")){
					result = "COMPLETED";
				} else if(status.equals("2")){
					result = "CANCELED";
				} else {
					result = "UN_FIND";
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			errlog.error("EmailAuthenticateService|userAuthenticate|异常：",e);
		}
		return result;
	}
	/**
	 * 发送验证邮件
	 * @param title
	 * @param content
	 * @param toUserAddress
	 * @return
	 */
	public boolean sendEmail(String title,String content,String toUserAddress){
		boolean result = false;
		try{
			Properties properties = new Properties(); 
			properties.setProperty("mail.smtp.auth", "true");// 服务器需要认证 
			properties.setProperty("mail.transport.protocol", sendProtocol);// 声明发送邮件使用的端口 
			properties.setProperty("mail.host", sendHostAddress);// 发送邮件的服务器地址 
			Session session = Session.getInstance(properties, new Authenticator() { 
			      protected PasswordAuthentication getPasswordAuthentication() { 
			        return new PasswordAuthentication(sendUserName, sendPassword); 
			      } 
			    }); 
		    session.setDebug(true);//在后台打印发送邮件的实时信息 
		  
		    Message message = new MimeMessage(session); 
		    message.setFrom(new InternetAddress(sendUserName)); 	//设置邮件发送人
		    message.setSubject(title);// 设置主题 
		    message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toUserAddress));   //设置邮件接收人
		    message.setContent(content,"text/html;charset=gbk");
		    Transport.send(message);//发送邮件 
		    result = true;
		} catch (Exception e) {
			e.printStackTrace();
			errlog.error("EmailAuthenticateService|sendEmail|异常：",e);
		}
		return result;
	}
	/**
	 * 格式化认证邮件内容
	 * @param logoImg		logo图片地址
	 * @param logoWidth		logo图片宽度
	 * @param logoHeight	logo图片高度
	 * @param btnText		按钮等文字内容
	 * @param hrefUrl		认证链接地址
	 * @return
	 */
	public String formatEmailContent(String logoImg,String logoWidth,String logoHeight,String btnText,String hrefUrl,String functionFlag){
		StringBuffer content = new StringBuffer();
	    content.append("<div style='width:800px;'>");
	    content.append("	<img src='"+logoImg+"' style='width:"+logoWidth+"px;height:"+logoHeight+"px;'/>");
	    content.append("	<div style='padding-left:50px;line-height:35px;font-size:16px;font-weight:900;WORD-WRAP: break-word;'>");
	    if(functionFlag.equals("sendEmailAuthenticate")){
	    	content.append("		请确认您的邮箱，只差一步，您的认证就成功了！<span style='color:#D0D0D0'> (请在24小时内完成)：</span>");
	    }else if(functionFlag.equals("sendEmailForResetPwd")){
	    	content.append("		请点击按钮或链接，只差一步，您就可以重置密码了！<span style='color:#D0D0D0'> (请在1小时内完成)：</span>");
	    }
	    content.append("		<div style='width:750px;text-align:center;padding-top:20px;padding-bottom:20px;'>");
	    content.append("			<a href='"+hrefUrl+"' style='text-decoration:none;'><div style='margin:0 auto;background-color:#FF3300;height:40px;line-height:40px;width:120px;color:#fff' >"+btnText+"</div></a>");
	    content.append("		</div>");
	    content.append("		<span style='color:#D0D0D0'>如果亲看不到上方的按钮<br/>可点击下面的链接以"+btnText+"或复制下面的链接到浏览器地址栏中"+btnText+"：</span>");
	    content.append("		<div style='WORD-WRAP: break-word;line-height:26px;'>");
	    content.append("			<a href='"+hrefUrl+"' style='text-decoration:none;color:#76A1FF'>"+hrefUrl+"</a>");
	    content.append("		</div>");
	    content.append("	</div>");
	    content.append("</div>");
	    return content.toString();
	}
}
